package com.lanhao.aot.aiui;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URI;
import java.util.Base64;

import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import com.google.gson.Gson;

/**
 * 窃取页面的音频信息
 */
public class WebTtsWsSpider {
    
    // 合成文本
    public static final String TEXT = "一本的春夏秋冬，半小时晚读，根据不同季节，来设定不同的主题，带着问题来阅读，能提高阅读理解能力，还能扫码听音频，在阅读中还可以积累好词好句，每天半小时朗读，让孩子爱上阅读，还能积累好词好句 搭配费曼学习法，让孩子从小养成，爱阅读的好习惯";
    // 合成文件名称
    public static final String OUTPUT_FILE_PATH = "src/main/resources/tts/" + System.currentTimeMillis() + ".pcm";
    // json
    public static final Gson gson = new Gson();
    public static boolean wsCloseFlag = false;
    
    // 需要替换一个鉴权的URL和请求的消息
    public static String wsUrl = "wss://tts-api.xfyun.cn/v2/tts?authorization=YXBpX2tleT0iZmI1MjVhZjJlNDNiNzIyNWU3YjFmYzAyMzA3YzljMTQiLCBhbGdvcml0aG09ImhtYWMtc2hhMjU2IiwgaGVhZGVycz0iaG9zdCBkYXRlIHJlcXVlc3QtbGluZSIsIHNpZ25hdHVyZT0iZG55SVR0cmNFVzZDK0M4MlFZV3NVRWdoNlgrN3gvbkdLYmRpYlpCcXFGST0i&date=Mon%2C%2013%20Nov%202023%2002%3A21%3A34%20GMT&host=tts-api.xfyun.cn";
    public static String requestJson = "{\"common\":{\"app_id\":\"5d50d68b\"},\"business\":{\"ent\":\"intp65\",\"aue\":\"raw\",\"auf\":\"audio/L16;rate=16000\",\"vcn\":\"x4_lingxiaolu_em_v2\",\"speed\":50,\"volume\":50,\"pitch\":50,\"bgs\":1,\"tte\":\"UTF8\"},\"data\":{\"status\":2,\"text\":\"5LiA5pys55qE5pil5aSP56eL5Yas77yM5Y2K5bCP5pe25pma6K+777yM5qC55o2u5LiN5ZCM5a2j6IqC77yM5p2l6K6+5a6a5LiN5ZCM55qE5Li76aKY77yM5bim552A6Zeu6aKY5p2l6ZiF6K+777yM6IO95o+Q6auY6ZiF6K+755CG6Kej6IO95Yqb77yM6L+Y6IO95omr56CB5ZCs6Z+z6aKR77yM5Zyo6ZiF6K+75Lit6L+Y5Y+v5Lul56ev57Sv5aW96K+N5aW95Y+l77yM5q+P5aSp5Y2K5bCP5pe25pyX6K+777yM6K6p5a2p5a2Q54ix5LiK6ZiF6K+777yM6L+Y6IO956ev57Sv5aW96K+N5aW95Y+lIOaQremFjei0ueabvOWtpuS5oOazle+8jOiuqeWtqeWtkOS7juWwj+WFu+aIkO+8jOeIsemYheivu+eahOWlveS5oOaDrw==\"}}";

    
    public static void main(String[] args) throws Exception {
        websocketWork(wsUrl, new FileOutputStream(OUTPUT_FILE_PATH));
    }

    // Websocket方法
    public static void websocketWork(String wsUrl, OutputStream outputStream) {
        try {
            URI uri = new URI(wsUrl);
            WebSocketClient webSocketClient = new WebSocketClient(uri) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("ws建立连接成功...");
                }

                @Override
                public void onMessage(String text) {
                    JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
                    if (myJsonParse.code != 0) {
                        System.out.println("发生错误，错误码为：" + myJsonParse.code);
                        System.out.println("本次请求的sid为：" + myJsonParse.sid);
                    }
                    if (myJsonParse.data != null) {
                        try {
                            byte[] textBase64Decode = Base64.getDecoder().decode(myJsonParse.data.audio);
                            outputStream.write(textBase64Decode);
                            outputStream.flush();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (myJsonParse.data.status == 2) {
                            try {
                                outputStream.close();
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                            System.out.println("本次请求的sid==>" + myJsonParse.sid);
                            System.out.println("合成成功，文件保存路径为==>" + OUTPUT_FILE_PATH);
                            // 可以关闭连接，释放资源
                            wsCloseFlag = true;
                        }
                    }
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("ws链接已关闭，本次请求完成...");
                }

                @Override
                public void onError(Exception e) {
                    System.out.println("发生错误 " + e.getMessage());
                }
            };
            // 建立连接
            webSocketClient.connect();
            while (!webSocketClient.getReadyState().equals(ReadyState.OPEN)) {
                //System.out.println("正在连接...");
                Thread.sleep(100);
            }
            webSocketClient.send(requestJson);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }

    //返回的json结果拆解
    class JsonParse {
        int code;
        String sid;
        Data data;
    }

    class Data {
        int status;
        String audio;
    }
}
